package uia.is202.template;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;



/**
 * The ExampleServlet doesn't do anything useful, but
 * it shows how to get parameter values from the request,
 * and how to store and retrive sesson and context attributes.
 *
 * @author Even Åby Larsen (even.larsen@uia.no)
 */
public class ExampleServlet  extends HttpServlet {


    /**
     * Handle get requests by calling processRequest()
     *
     * @param req the request object
     * @param resp the response object
     *
     * @throws IOException if writing the response fails.
     * @throws ServletException if anything else fails and graceful recovery is impossible.
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        processRequest(req, resp);
    }


    /**
     * Handle post requests by calling processRequest()
     *
     * @param req the request object
     * @param resp the response object
     *
     * @throws IOException if writing the response fails.
     * @throws ServletException if anything else fails and graceful recovery is impossible.
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        processRequest(req, resp);
    }


    /**
     * This method handles both GET and PUT requests (because
     * it is called from the doGet() and doPost() methods.
     *
     * @param httpReq The request object.
     * @param response The response object.
     * @throws IOException DOCUMENT WHEN!!
     * @throws ServletException DOCUMENT WHEN!!
     */
    protected void processRequest(HttpServletRequest req,
                                  HttpServletResponse res)
            throws ServletException, IOException {
        // Always get the session object first.
        HttpSession session = req.getSession();

        // Try to get Norwegian characters right
        req.setCharacterEncoding("UTF-8");
        res.setCharacterEncoding("UTF-8");
        res.setHeader("Content-Type", "text/html;charset=UTF-8");
        res.setHeader("Cache-Control", "no-cache");
        res.setHeader("Expires", "0");
        res.setContentType("text/html;charset=UTF-8");

        // Get a request parameter:
        String message = req.getParameter("message");

        // Get a session attribute
        String prevMessage = (String)session.getAttribute("prevMessage");

        // Set the value of a session attribute
        session.setAttribute("prevMessage", message);

        // Get a context attribute
        ServletContext context = getServletContext();
        ArrayList<String> messages = (ArrayList<String>)context.getAttribute("messages");

        // getAttribute returns null if the attribute doesn't exist
        // if we really need the attribute value we must check the
        // value and create the object if it is null
        if (messages == null) messages = new ArrayList<String>();
        context.setAttribute("messages", messages);

        messages.add(message);

        // Write the page
        PrintWriter out = res.getWriter();
        out.println("<html>");
        out.println("<head><title>IS-202 Example Servlet</title></head>");
        out.println("<body>");
        out.println("<h1>IS-202 Example Servlet</h1>");

        out.println("<table>");
        out.print("<tr><td>Your message was:</td>");
        out.println("<td>"+message+"</td></tr>");
        if (prevMessage != null) {
            out.print("<tr><td>Your previous message was:</td>");
            out.println("<td>"+prevMessage+"</td></tr>");
        }
        out.print("<tr><td>All messages I've got:</td>");
        out.print("<td>");
        for (String m : messages) out.print(m+";");
        out.println("</td></tr>");
        out.println("</table>");

        // form for new message
        out.println("<form action=\"example\">");
        out.println("<p>Enter new message: <input name=\"message\"/></p>");
        out.println("<input type=\"submit\" value=\"Send it to the example servlet\"/>");
        out.println("</form>");

        out.println("</body>\n</html>");
    }

}
